import React, { useState } from 'react';
import { Card, Collapse, Tag, Space, Button, Empty, Tooltip, Input } from 'antd';
import { 
  DatabaseOutlined, 
  UserOutlined, 
  MailOutlined, 
  SearchOutlined,
  CopyOutlined,
  PlusOutlined 
} from '@ant-design/icons';
import { message } from 'antd';

const { Panel } = Collapse;
const { Search } = Input;

interface Variable {
  name: string;
  display_name: string;
  field_type: string;
  is_email: boolean;
  is_name: boolean;
  sample_value?: string;
  description?: string;
  data_nature?: 'static' | 'dynamic'; // 数据特性：静态或动态
}

interface VariablePanelProps {
  variables: Variable[];
  onVariableClick?: (variableName: string) => void;
  onVariableDrag?: (variableName: string) => void;
  loading?: boolean;
  title?: string;
}

const VariablePanel: React.FC<VariablePanelProps> = ({
  variables = [],
  onVariableClick,
  onVariableDrag,
  loading = false,
  title = '可用变量',
}) => {
  const [searchText, setSearchText] = useState('');
  const [activeKey, setActiveKey] = useState<string[]>(['email', 'name', 'other']);

  // 过滤变量
  const filteredVariables = variables.filter(variable =>
    variable.name.toLowerCase().includes(searchText.toLowerCase()) ||
    variable.display_name.toLowerCase().includes(searchText.toLowerCase()) ||
    (variable.description && variable.description.toLowerCase().includes(searchText.toLowerCase()))
  );

  // 先按表分组，再按字段类型分组
  const groupedByTable = filteredVariables.reduce((acc, variable) => {
    // 提取表名（如果有表名前缀）
    const tableName = variable.name.includes('.')
      ? variable.name.split('.')[0]
      : 'default';

    if (!acc[tableName]) {
      acc[tableName] = {
        email: [],
        name: [],
        number: [],
        string: [],
        date: [],
        boolean: [],
        other: []
      };
    }

    // 按字段类型分类
    if (variable.is_email) {
      acc[tableName].email.push(variable);
    } else if (variable.is_name) {
      acc[tableName].name.push(variable);
    } else {
      switch (variable.field_type) {
        case 'number':
          acc[tableName].number.push(variable);
          break;
        case 'string':
          acc[tableName].string.push(variable);
          break;
        case 'date':
          acc[tableName].date.push(variable);
          break;
        case 'boolean':
          acc[tableName].boolean.push(variable);
          break;
        default:
          acc[tableName].other.push(variable);
      }
    }

    return acc;
  }, {} as Record<string, Record<string, Variable[]>>);

  const handleVariableClick = (variableName: string) => {
    onVariableClick?.(variableName);
    message.success(`已插入变量: {{${variableName}}}`);
  };

  const handleCopyVariable = (variableName: string, e: React.MouseEvent) => {
    e.stopPropagation();
    navigator.clipboard.writeText(`{{${variableName}}}`);
    message.success('变量已复制到剪贴板');
  };

  const getFieldTypeColor = (type: string) => {
    switch (type) {
      case 'string': return 'blue';
      case 'number': return 'green';
      case 'date': return 'orange';
      case 'boolean': return 'purple';
      case 'email': return 'cyan';
      default: return 'default';
    }
  };

  const getFieldTypeLabel = (type: string) => {
    switch (type) {
      case 'string': return '文本';
      case 'number': return '数字';
      case 'date': return '日期';
      case 'boolean': return '布尔';
      case 'email': return '邮箱';
      default: return type;
    }
  };

  // 判断数据特性：静态 vs 动态
  const getDataNature = (variable: Variable): 'static' | 'dynamic' => {
    // 如果已经明确标识，直接返回
    if (variable.data_nature) {
      return variable.data_nature;
    }

    // 基础字段通常是静态的
    if (variable.is_email || variable.is_name) {
      return 'static';
    }

    // 根据字段名判断
    const dynamicKeywords = ['balance', 'amount', 'quantity', 'stock', 'status', 'count', 'total', 'price', 'score', 'point'];
    const staticKeywords = ['name', 'email', 'phone', 'address', 'company', 'department', 'position', 'title'];

    const fieldName = variable.name.toLowerCase();

    if (dynamicKeywords.some(keyword => fieldName.includes(keyword))) {
      return 'dynamic';
    }

    if (staticKeywords.some(keyword => fieldName.includes(keyword))) {
      return 'static';
    }

    // 默认根据字段类型判断：数字类型倾向于动态，其他倾向于静态
    return variable.field_type === 'number' ? 'dynamic' : 'static';
  };

  const renderVariableItem = (variable: Variable) => (
    <div
      key={variable.name}
      style={{
        padding: '8px 12px',
        border: '1px solid #f0f0f0',
        borderRadius: '4px',
        marginBottom: '8px',
        cursor: 'pointer',
        transition: 'all 0.2s',
        backgroundColor: '#fafafa',
      }}
      onClick={() => handleVariableClick(variable.name)}
      onMouseEnter={(e) => {
        e.currentTarget.style.backgroundColor = '#e6f7ff';
        e.currentTarget.style.borderColor = '#1890ff';
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.backgroundColor = '#fafafa';
        e.currentTarget.style.borderColor = '#f0f0f0';
      }}
      draggable
      onDragStart={(e) => {
        e.dataTransfer.setData('text/plain', `{{${variable.name}}}`);
        onVariableDrag?.(variable.name);
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <Space>
          {variable.is_email && <MailOutlined style={{ color: '#1890ff' }} />}
          {variable.is_name && <UserOutlined style={{ color: '#52c41a' }} />}
          {!variable.is_email && !variable.is_name && <DatabaseOutlined style={{ color: '#666' }} />}
          <span style={{ fontWeight: 500 }}>
            {variable.display_name || variable.name}
          </span>
        </Space>
        <Space>
          <Tag size="small" color={getFieldTypeColor(variable.field_type)}>
            {getFieldTypeLabel(variable.field_type)}
          </Tag>
          {/* 数据特性标识 */}
          <Tag
            size="small"
            color={getDataNature(variable) === 'static' ? 'green' : 'orange'}
          >
            {getDataNature(variable) === 'static' ? '📌静态' : '🔄动态'}
          </Tag>
          <Tooltip title="复制变量">
            <Button
              type="text"
              size="small"
              icon={<CopyOutlined />}
              onClick={(e) => handleCopyVariable(variable.name, e)}
            />
          </Tooltip>
        </Space>
      </div>
      
      {variable.sample_value && (
        <div style={{ marginTop: '4px', fontSize: '12px', color: '#999' }}>
          示例: {variable.sample_value}
        </div>
      )}
      
      {variable.description && (
        <div style={{ marginTop: '4px', fontSize: '12px', color: '#666' }}>
          {variable.description}
        </div>
      )}

      {/* 数据特性说明 */}
      <div style={{ marginTop: '4px', fontSize: '11px', color: getDataNature(variable) === 'static' ? '#52c41a' : '#fa8c16' }}>
        {getDataNature(variable) === 'static'
          ? '📌 静态数据：相对稳定，适合批量发送'
          : '🔄 动态数据：可能变化，建议实时获取'
        }
      </div>

      <div style={{ marginTop: '4px', fontSize: '11px', color: '#ccc', fontFamily: 'monospace' }}>
        {`{{${variable.name}}}`}
      </div>
    </div>
  );

  const renderVariableGroup = (groupKey: string, groupVariables: Variable[], icon: React.ReactNode, title: string) => {
    if (groupVariables.length === 0) return null;

    return (
      <Panel
        header={
          <Space>
            {icon}
            <span>{title}</span>
            <Tag size="small">{groupVariables.length}</Tag>
          </Space>
        }
        key={groupKey}
      >
        {groupVariables.map(renderVariableItem)}
      </Panel>
    );
  };

  const getFieldTypeIcon = (type: string) => {
    switch (type) {
      case 'email': return <MailOutlined style={{ color: '#1890ff' }} />;
      case 'name': return <UserOutlined style={{ color: '#52c41a' }} />;
      case 'number': return <span style={{ color: '#fa8c16' }}>#</span>;
      case 'string': return <span style={{ color: '#722ed1' }}>T</span>;
      case 'date': return <span style={{ color: '#eb2f96' }}>📅</span>;
      case 'boolean': return <span style={{ color: '#13c2c2' }}>✓</span>;
      default: return <DatabaseOutlined style={{ color: '#666' }} />;
    }
  };

  const getFieldTypeTitle = (type: string) => {
    switch (type) {
      case 'email': return '邮箱字段';
      case 'name': return '姓名字段';
      case 'number': return '数字字段';
      case 'string': return '文本字段';
      case 'date': return '日期字段';
      case 'boolean': return '布尔字段';
      default: return '其他字段';
    }
  };

  return (
    <Card
      title={
        <Space>
          <DatabaseOutlined />
          {title}
          {variables.length > 0 && <Tag>{variables.length}</Tag>}
        </Space>
      }
      size="small"
      loading={loading}
      style={{
        height: '600px', // 固定高度
        position: 'sticky',
        top: '20px'
      }}
      bodyStyle={{
        padding: '12px',
        height: 'calc(100% - 57px)',
        overflowY: 'auto',
        overflowX: 'hidden',
        // 确保滚动条样式
        scrollbarWidth: 'thin',
        scrollbarColor: '#d9d9d9 #f0f0f0'
      }}
    >
      {variables.length === 0 ? (
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description="暂无可用变量"
          style={{ marginTop: '40px' }}
        >
          <p style={{ color: '#999', fontSize: '12px' }}>
            请先选择数据源和表
          </p>
        </Empty>
      ) : (
        <>
          <Search
            placeholder="搜索变量..."
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ marginBottom: '12px' }}
            size="small"
          />
          
          <Collapse
            activeKey={activeKey}
            onChange={(keys) => setActiveKey(keys as string[])}
            size="small"
            ghost
          >
            {Object.entries(groupedByTable).map(([tableName, tableFields]) => (
              <Panel
                header={
                  <Space>
                    <DatabaseOutlined style={{ color: '#1890ff' }} />
                    <span>{tableName === 'default' ? '默认表' : tableName}</span>
                    <Tag size="small">
                      {Object.values(tableFields).reduce((sum, fields) => sum + fields.length, 0)}
                    </Tag>
                  </Space>
                }
                key={`table-${tableName}`}
              >
                <Collapse size="small" ghost>
                  {Object.entries(tableFields).map(([fieldType, fields]) =>
                    renderVariableGroup(
                      `${tableName}-${fieldType}`,
                      fields,
                      getFieldTypeIcon(fieldType),
                      getFieldTypeTitle(fieldType)
                    )
                  )}
                </Collapse>
              </Panel>
            ))}
          </Collapse>
          
          <div style={{ marginTop: '12px', padding: '8px', backgroundColor: '#f9f9f9', borderRadius: '4px' }}>
            <p style={{ margin: 0, fontSize: '12px', color: '#666' }}>
              💡 使用提示：
            </p>
            <ul style={{ margin: '4px 0 0 0', paddingLeft: '16px', fontSize: '11px', color: '#999' }}>
              <li>点击变量直接插入到编辑器</li>
              <li>拖拽变量到编辑器指定位置</li>
              <li>在编辑器中输入 {'{{'} 自动提示</li>
            </ul>
          </div>
        </>
      )}
    </Card>
  );
};

export default VariablePanel;
